import md5 from 'js-md5'

let AsyncJson = function (type, url, data) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open(type,"http://chatservice.linkin.cn:11659/api/" + url,true);
    xhr.onreadystatechange =  () => {
      if(xhr.readyState === 4){
        if(xhr.status === 200){
          resolve(JSON.parse(xhr.responseText));
        }else{
          reject(xhr);
        }
      }
    };
    if (type.toLowerCase() === 'get') {
      xhr.send()
    } else if (type.toLowerCase() === 'post') {
      xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      data["request_date"] = parseInt((Date.parse(new Date()) + "").substr(0,10)) - sessionStorage.getItem("tempTime");
      xhr.send(formatParams(data));
    }
  });
};

function formatParams(data) {
  let arr = [];
  for(let name in data){
    arr.push(name + '=' + data[name]);
  }
  arr.push("auth_sign=" + getAuth(data));
  return arr.join("&");
}

// 获取 auth_sign
function getAuth(obj) {
  let arr=[];
  for(let k in obj){
    arr.push(k);
  }
  arr.sort();
  let str='';
  for(let i in arr){
    str +=arr[i]+obj[arr[i]]
  }
  return md5(str + "f324d7dc80fac0495bfff170f6957768");
}

export default AsyncJson
